package com.ccp.dev.system.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.CollectionUtil;
import com.ccp.dev.core.util.Convert;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.system.model.IndexColumn;
import com.ccp.dev.system.model.IndexLayout;
import com.ccp.dev.system.model.IndexLayoutManage;
import com.ccp.dev.system.service.IndexColumnService;
import com.ccp.dev.system.service.IndexLayoutManageService;
import com.ccp.dev.system.service.IndexLayoutService;

import com.ccp.dev.system.service.SysOrgService;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页布局管理 信息操作处理
 *
 * @author doufangzheng
 * @date 2019-03-27
 */
@Controller
@Action(ownermodel = SysAuditModelType.HOME_MANAGEMENT)
@RequestMapping(UrlConstants.PROJECT_ROOT+UrlConstants.PROJECT_MODULE_SYSTEM+"/indexLayoutManage")
public class IndexLayoutManageController extends SysBaseController {

    @Autowired
    private IndexLayoutManageService indexLayoutManageService;
    
    @Autowired
    private IndexLayoutService indexLayoutService;

    @Autowired
    private IndexColumnService indexColumnService;

    @Autowired
    private SysOrgService sysOrgService;

    /**
     * 查询布局管理列表
     * @param request 请求
     * @return 返回封装对象
     */
    @GetMapping("/list")
    @ResponseBody
    @Action(description="查询布局管理",detail="查询布局管理<#if success>成功<#else>失败</#if>",exectype = "查询日志")
    public ResultData list(HttpServletRequest request){
        try{
            SysAuditThreadLocalHolder.putParamerter("success", true);
            QueryFilter queryFilter = new QueryFilter(request);
            List<IndexLayoutManage> list = indexLayoutManageService.queryList(queryFilter);
            return getResultDataSuccess("operation.success",queryFilter.getPageBean().getTotalCount(),list);
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 新增及修改首页布局
     * @param indexLayoutManage	首页布局对象
     * @ResponseBody
     * @return 返回ResultData对象
     */
    @PostMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @Action(description="保存布局管理",detail="<#if StringUtil.isEmpty(id)>新增<#else>更新</#if>布局管理【${name}】<#if success>成功<#else>失败</#if>",exectype = "编辑日志")
    @ResponseBody
    public ResultData save(@RequestBody IndexLayoutManage indexLayoutManage) {
        indexLayoutManage.setTemplateHtml(StringEscapeUtils.unescapeHtml4(indexLayoutManage.getTemplateHtml()));
        indexLayoutManage.setDesignHtml(StringEscapeUtils.unescapeHtml4(indexLayoutManage.getDesignHtml()));
       try{
           String name = indexLayoutManage.getName();
           String id = indexLayoutManage.getId();
           SysAuditThreadLocalHolder.putParamerter("success", true);
           SysAuditThreadLocalHolder.putParamerter("name", name);
           SysAuditThreadLocalHolder.putParamerter("id", id);
           if (StringUtils.isEmpty(name)) {
               SysAuditThreadLocalHolder.putParamerter("success", false);
               return ResultData.error("名称不能为空");
           }

           IndexLayoutManage i = new IndexLayoutManage();
           i.setName(indexLayoutManage.getName());
           List<IndexLayoutManage> list = indexLayoutManageService.selectIndexLayoutManageList(i);

           indexLayoutManage.setOrgId(sysOrgService.getOrgByUserId(ContextUtil.getCurrentUserId()).getOrgId());
           indexLayoutManage.setOrgName(sysOrgService.getOrgByUserId(ContextUtil.getCurrentUserId()).getOrgName());
           // 有id为新增，否则为修改
           // 新增
           if (StringUtils.isEmpty(id)) {
               // 校验名称是否存在
               if (BeanUtils.isNotEmpty(list)) {
                   SysAuditThreadLocalHolder.putParamerter("success", false);
                   return ResultData.error("名称已存在");
               }
               indexLayoutManage.setId(UUIDUtils.getUUIDFor32());
               indexLayoutManageService.add(indexLayoutManage);
           } else {	// 修改
               // 如果有id不同并且名称相同的，则修改失败
               if (BeanUtils.isNotEmpty(list)) {
                   for (IndexLayoutManage layout : list) {
                       if (!layout.getId().equals(indexLayoutManage.getId()) && layout.getName().equals(indexLayoutManage.getName())) {
                           SysAuditThreadLocalHolder.putParamerter("success", false);
                           return ResultData.error("名称已存在");
                       }
                   }
               }
               indexLayoutManageService.update(indexLayoutManage);
           }
           return ResultData.success();
       }catch (Exception e){
           SysAuditThreadLocalHolder.putParamerter("success", false);
           return ResultData.error();
       }
    }

    /**
     * 删除布局
     * @return 返回ResultData对象
     */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description="删除布局管理",detail="删除布局管理<#if success><#list name as item>【${item}】</#list>成功<#else>失败</#if>",exectype = "删除日志")
    public ResultData del(String ids) {
        try{
            SysAuditThreadLocalHolder.putParamerter("success", true);
            if (StringUtils.isEmpty(ids)) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return ResultData.error("没有id传入");
            }
            String[] idArr = StringUtils.split(ids, ",");
            SysAuditThreadLocalHolder.putParamerter("name",indexLayoutManageService.queryIndexColumnNameByIds(idArr));
            indexLayoutManageService.delByIdArray(idArr);
            return ResultData.success();
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return ResultData.error();
        }
    }

    /**
     * 取得一条布局记录
     * @return ResultData
     */
    @ResponseBody
    @GetMapping(UrlConstants.MODULE_FUNCTION_GET)
    @Action(description="查询布局明细",detail="查询布局明细<#if success>【${name}】成功<#else>失败</#if>",exectype = "查询日志")
    public ResultData get(String id) {
        try{
            SysAuditThreadLocalHolder.putParamerter("success", true);
            if (StringUtils.isEmpty(id)) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return ResultData.error("id不能为空");
            }
            IndexLayoutManage indexLayoutManage = indexLayoutManageService.getOneById(id);
            SysAuditThreadLocalHolder.putParamerter("name", indexLayoutManage.getName());
            return ResultData.success(indexLayoutManage);
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return ResultData.error();
        }
    }

    @ResponseBody
    @GetMapping("/layoutList")
    @Action(description="查询所有首页布局与栏目列表",detail="查询所有首页布局与栏目列表<#if success>成功<#else>失败</#if>",exectype = "查询日志")
    public ResultData layoutList(HttpServletRequest request) {
    	try{
            SysAuditThreadLocalHolder.putParamerter("success", true);
            QueryFilter queryFilter = new QueryFilter(request, false);
            List<IndexColumn> indexColumnList = indexColumnService.queryIndexColumnList(queryFilter);

            List<IndexLayout> IndexLayoutList = indexLayoutService.queryList(queryFilter);

            List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();

            Map<String, Object> IndexLayoutManageMap = new HashMap<String, Object>();
            IndexLayoutManageMap.put("data", IndexLayoutList);
            IndexLayoutManageMap.put("listName", "布局设置");
            result.add(IndexLayoutManageMap);

            Map<String, Object> indexColumnMap = new HashMap<String, Object>();
            indexColumnMap.put("data", indexColumnList);
            indexColumnMap.put("listName", "默认栏目");
            result.add(indexColumnMap);
            return ResultData.success(result);
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return ResultData.error("operation.failure");
        }
    }

    /**
     * 新增应用首页布局
     * @return ResultData
     */
    @ResponseBody
    @PostMapping("/apply")
    @Action(description="新增应用首页布局",detail="新增应用首页布局<#if success>成功<#else>失败</#if>",exectype = "编辑日志")
    public ResultData apply(String id) {
        try{
            SysAuditThreadLocalHolder.putParamerter("success", true);
            if (StringUtils.isEmpty(id)) {
                return ResultData.error("id不能为空");
            }
            indexLayoutManageService.apply(id);
            return getResultDataSuccess("operation.success");
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataSuccess("operation.failure");
        }
    }
    
    /*-------------以下是页面跳转------------------------*/
    /**
     * 跳转到布局管理列表页
     * @return html文件前缀
     */
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX+"/list")
    @Action(description="首页布局管理列表页面跳转",exectype = "页面跳转日志")
    public String viewIndexLayoutManageList(){
        return "sysIndexConfig/layoutManage/list";
    }
    /**
     * 跳转到布局管理添加页
     * @return html文件前缀
     */
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX+"/edit")
    @Action(description="首页布局管理编辑页面跳转",exectype = "页面跳转日志")
    public String viewIndexLayoutManageAdd(String id, Model model){
    	model.addAttribute("id", id);
        return "sysIndexConfig/layoutManage/addEdit";
    }
    
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX+"/customLayout")
    @Action(description="首页布局管理编辑2页面跳转",exectype = "页面跳转日志")
    public String customLayout(String id, Model model){
    	model.addAttribute("id", id);
        return "sysIndexConfig/layoutManage/customLayout";
    }

    /**
     * 跳转到布局管理查看页
     * @return html文件前缀
     */
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX+"/view")
    @Action(description="首页布局管理查看页面跳转",exectype = "页面跳转日志")
    public String viewIndexLayoutManageView(String id, Model model){
    	model.addAttribute("id", id);
        return "sysIndexConfig/layoutManage/view";
    }
    
    @ResponseBody
    @GetMapping("/getOneOrDefault")
    @Action(description="获取布局明细或默认首页布局",detail="获取布局明细或默认首页布局<#if success>成功<#else>失败</#if>",exectype = "查询日志")
    public ResultData getOneOrDefault(String id) {
        try{
            SysAuditThreadLocalHolder.putParamerter("success", true);
            if (StringUtils.isEmpty(id)) {
                IndexLayoutManage indexLayoutManage = new IndexLayoutManage();
                indexLayoutManage.setIsDef(1);
                List<IndexLayoutManage> list = indexLayoutManageService.selectIndexLayoutManageList(indexLayoutManage);
                if (!CollectionUtil.isEmpty(list)) {
                    return ResultData.success("首页内容", list.get(0));
                }
            }
            IndexLayoutManage indexLayoutManage = indexLayoutManageService.getOneById(id);
            return ResultData.success(indexLayoutManage);
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return ResultData.error();
        }
    }
}
